﻿namespace Vboot.Core.Module.Sys;

[ApiDescriptionSettings("Sys", Tag = "合作伙伴-用户账号")]
public class SysCoopUserApi : IDynamicApiController
{
    private readonly SysCoopUserService _service;
    
    private readonly SysCoopCorpService _corpService;

    public SysCoopUserApi(SysCoopUserService service,
        SysCoopCorpService corpService)
    {
        _service = service;
        _corpService = corpService;
    }
    
    public async Task<dynamic> GetList()
    {
        return await _service.repo.GetListAsync();
    }

    
    /// <summary>
    /// 获取分页数据
    /// </summary>
    /// <returns></returns>
    [QueryParameters]
    public async Task<dynamic> Get(string name,string corid)
    {
        var pp = XreqUtil.GetPp();
        var items  = await _service.repo.Context.Queryable<SysCoopUser, SysOrg, SysOrg,SysCoopCorp>
            ((t, o, o2,c) => new JoinQueryInfos(
                JoinType.Left, o.id == t.crmid,
                JoinType.Left, o2.id == t.upmid,
                JoinType.Left, c.id == t.corid))
            .WhereIF(!string.IsNullOrWhiteSpace(name), t => t.name.Contains(name.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(corid), t => t.corid==corid)
            .OrderBy(t => t.crtim, OrderByType.Desc)
            .Select((t, o, o2,c)
                =>  (dynamic) new {t.id, t.name, t.notes, t.crtim, t.uptim, t.type,crman = o.name, upman = o2.name,corna=c.name})
            .ToPageListAsync(pp.page, pp.pageSize, pp.total);
        return RestPageResult.Build(pp.total.Value, items);
    }
    
    public async Task<SysCoopUser> GetOne(string id)
    {
        var user = await _service.SingleAsync(id);
        if (user.corid != null)
        {
            user.corp = await _corpService.SingleAsync(user.corid);
        }
        return user;
    }

    public async Task<string> Post(SysCoopUser main)
    {
        main.pacod = SecureUtils.PasswordEncrypt(main.pacod);
        return await _service.Insert(main);
    }

    public async Task<string> Put(SysCoopUser main)
    {
        return await _service.Update(main);
    }

    public async Task Delete(string ids)
    {
        await _service.Delete(ids);
    }
    
    public async Task PostPacod(PacodPo po)
    {
        await _service.ResetPacod(po);
    }

}